#!/bin/sh

#create databases
mysql -uroot -p$RDS_PASSWD -e"create database IF NOT EXISTS $RDS_DB default character set utf8;"

#download tomcat
if [ ! -e $HOME/.download ];then
    mkdir $HOME/.download;
fi;
mkdir $HOME/.tomcat;
if [ ! -e $HOME/.download/tomcat8.zip ];then
    wget -O $HOME/.download/tomcat8.zip  https://raw.githubusercontent.com/289048093/mvn/mvn-repo/tomcat/apache-tomcat-8.0.26.zip;
fi;
unzip  $HOME/.download/tomcat8.zip -d $HOME/.tomcat;
sudo chmod -R +x $HOME/.tomcat/apache-tomcat-8.0.26/bin

#package war
mvn -DskipTests=true package
cp $EXTERNAL_WAR  $HOME/.tomcat/apache-tomcat-8.0.26/webapps/external.war
cp $INTERNAL_WAR  $HOME/.tomcat/apache-tomcat-8.0.26/webapps/internal.war

# start tomcat
sh $HOME/.tomcat/apache-tomcat-8.0.26/bin/startup.sh

# wait for tomcat started
for i in $(seq 60);do
    curl -I 127.0.0.1:8080/external/version|grep "200 OK";
    if [ $? -eq 0 ]; then
        echo "connect tomcat success";
        break;
    elif [ $i -eq 60 ]; then
        echo "connect tomcat timeout";
        exit 1;
    fi;
    sleep 1;
done;

#print log
cat $HOME/.tomcat/apache-tomcat-8.0.26/logs/catalina.out;
mysql -uroot -p$RDS_PASSWD -D$RDS_DB -e"select * from t_db_version";

# check db-schema exec-status
if [ `mysql -uroot -p$RDS_PASSWD -D$RDS_DB -e"select status from t_db_version"|awk 'BEGIN{res=2} NR==2{res=$1} END{print res}'` -ne 0 ]; then
    echo "db schema status error...";
    exit 1;
fi;